//
//  AudioControlBar.swift
//  LeTu
//
//  Created by g1 on 2024/1/15.
//

import UIKit

class AudioControlBar: UIView {

    private var isPlaying = false
    var clickActionHandle: ((String) -> Void)?
    var sliderValueChangeHandle: ((Float) -> Void)?
    var sliderValueEndHandle: ((Float) -> Void)?
    var clickListHandle: (() -> Void)?
    var isChangeSlider = false
    private var totalTime: Float = 0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        configUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        configUI()
    }
    // 更新界面文字
    func exchangeLanguage() {
        speedButton.setTitle("倍速".localized)
        
        speedButton.snp.updateConstraints { make in
            make.width.equalTo(LanguageManager.shared.currentLanguage == .zh ? 44:54)
        }
    }
    // 设置播放状态
    func setIsplaying(isPlaying: Bool) {
        let imageName = isPlaying ? "audio_suspend" : "audio_play"
        playPauseButton.setImage(UIImage(named: imageName))
    }
    // 设置总时长
    func setTotalTime(time: Float) {
        self.totalTime = time
        
        let timeText = AppAudioManager.shared.formatTimeFromSeconds(seconds: Double(time))
        totalTimeLabel.attributed.text = "\(timeText, .kern(0.8))"
        currentTimeLabel.attributed.text = "\((timeText.count > 5 ? "00:00:00" : "00:00"), .kern(0.8))"
    }
    func setCurrentTime(time: String) {
        currentTimeLabel.attributed.text = "\(time, .kern(0.8))"
    }
    // 设置当前播放进度
    func setSeek(_ seek: Float) {
        progressSlider.value = seek
    }
    
    // MARK: - Button Actions
    @objc private func previousButtonTapped() {
        guard let actionHandle = clickActionHandle else { return }
        actionHandle("上一首")
    }
    
    @objc private func playPauseButtonTapped() {
        
        guard let actionHandle = clickActionHandle else { return }
        actionHandle("播放")
    }
    
    @objc private func nextButtonTapped() {
        guard let actionHandle = clickActionHandle else { return }
        actionHandle("下一首")
    }
    
    @objc private func progressSliderValueStart() {
        isChangeSlider = true
    }
    
    @objc private func progressSliderValueChanged() {
        
        currentTimeLabel.text = AppAudioManager.shared.formatTimeFromSeconds(seconds: Double(totalTime*progressSlider.value))
        
        guard let valueChangedHandle = sliderValueChangeHandle else { return }
        valueChangedHandle(progressSlider.value)
    }
    
    @objc private func progressSliderValueEnd() {
        guard let valueChangedHandle = sliderValueEndHandle else { return isChangeSlider = false }
        valueChangedHandle(progressSlider.value)
    }
    
    @objc func speedButtonAction() {
        speedListView.isHidden = !speedListView.isHidden
    }
    
    @objc func playListButtonAction() {
        guard let handle = clickListHandle else { return }
        handle()
    }
    
    // MARK: - configUI
    func configUI() {
        
        addSubview(progressBackView)
        progressBackView.addSubview(currentTimeLabel)
        progressBackView.addSubview(totalTimeLabel)
        progressBackView.addSubview(progressSlider)
        addSubview(controlBackView)
        controlBackView.addSubview(playPauseButton)
        controlBackView.addSubview(previousButton)
        controlBackView.addSubview(nextButton)
        addSubview(speedButton)
        addSubview(playListButton)
        addSubview(speedListView)
        
        progressBackView.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.top.equalToSuperview()
            make.height.equalTo(20)
        }
        currentTimeLabel.snp.makeConstraints { make in
            make.left.centerY.equalToSuperview()
            make.width.greaterThanOrEqualTo(34)
        }
        totalTimeLabel.snp.makeConstraints { make in
            make.right.centerY.equalToSuperview()
            make.width.greaterThanOrEqualTo(34)
        }
        progressSlider.snp.makeConstraints { make in
            make.leading.equalTo(currentTimeLabel.snp.trailing).offset(6)
            make.trailing.equalTo(totalTimeLabel.snp.leading).offset(-6)
            make.centerY.equalToSuperview()
        }
        controlBackView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(progressBackView.snp.bottom).offset(36)
            make.height.equalTo(60)
        }
        playPauseButton.snp.makeConstraints { make in
            make.top.bottom.centerX.equalToSuperview()
            make.width.equalTo(playPauseButton.snp.height)
        }
        previousButton.snp.makeConstraints { make in
            make.left.centerY.equalToSuperview()
            make.right.equalTo(playPauseButton.snp.left).offset(-52)
        }
        nextButton.snp.makeConstraints { make in
            make.left.equalTo(playPauseButton.snp.right).offset(52)
            make.centerY.right.equalToSuperview()
        }
        speedButton.snp.makeConstraints { make in
            make.left.equalTo(22)
            make.centerY.equalTo(controlBackView)
            make.width.equalTo(44)
            make.height.equalTo(22)
        }
        playListButton.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.centerY.equalTo(controlBackView)
            make.width.equalTo(20+22*2)
            make.height.equalTo(16+22*2)
        }
        speedListView.snp.makeConstraints { make in
            make.width.equalTo(speedListView.getSpeedViewWidth())
            make.bottom.equalTo(playPauseButton.snp.top)
            make.left.equalTo(speedButton)
            make.height.equalTo(36)
        }
        
        previousButton.addTarget(self, action: #selector(previousButtonTapped))
        playPauseButton.addTarget(self, action: #selector(playPauseButtonTapped))
        nextButton.addTarget(self, action: #selector(nextButtonTapped))
        progressSlider.addTarget(self, action: #selector(progressSliderValueStart), for: .touchDown)
        progressSlider.addTarget(self, action: #selector(progressSliderValueChanged), for: .valueChanged)
        progressSlider.addTarget(self, action: #selector(progressSliderValueEnd), for: .touchUpInside)
        progressSlider.addTarget(self, action: #selector(progressSliderValueEnd), for: .touchUpOutside)
        speedButton.addTarget(self, action: #selector(speedButtonAction))
        playListButton.addTarget(self, action: #selector(playListButtonAction))
        
        currentTimeLabel.text = "00:00:00"
        totalTimeLabel.text = "00:00:00"
        
        speedListView.isHidden = true
        
        exchangeLanguage()
    }
    private lazy var progressBackView = UIView()
    private lazy var progressSlider: MarkSlider = {
        let progressSlider = MarkSlider()
        progressSlider.setThumbImage(UIImage(named: "slider_block"), for: .normal)
        progressSlider.leftBarColor = UIColor.hex(hexString: "D9D9D9")
        progressSlider.rightBarColor = UIColor.hex(hexString: "D9D9D9").withAlphaComponent(0.23)
        return progressSlider
    }()
    private lazy var currentTimeLabel: UILabel = {
        let currentTimeLabel = UILabel()
        currentTimeLabel.font = kSetPingFangRegular(10)
        currentTimeLabel.textColor = .white
        currentTimeLabel.textAlignment = .center
        return currentTimeLabel
    }()
    private lazy var totalTimeLabel: UILabel = {
        let totalTimeLabel = UILabel()
        totalTimeLabel.font = kSetPingFangRegular(10)
        totalTimeLabel.textColor = .white
        totalTimeLabel.textAlignment = .center
        return totalTimeLabel
    }()
    private lazy var controlBackView = UIView()
    private lazy var previousButton: CustomClickableView = {
        let previousButton = CustomClickableView()
        previousButton.setImage(UIImage(named: "audio_play_last"))
        return previousButton
    }()
    private lazy var playPauseButton: CustomClickableView = {
        let playPauseButton = CustomClickableView()
        playPauseButton.setImage(UIImage(named: "audio_play"))
        return playPauseButton
    }()
    private lazy var nextButton: CustomClickableView = {
        let nextButton = CustomClickableView()
        nextButton.setImage(UIImage(named: "audio_play_next"))
        return nextButton
    }()
    private(set) lazy var speedButton: CustomClickableView = {
        let speedButton = CustomClickableView()
        speedButton.setFont(kSetPingFangRegular(14))
        speedButton.layer.cornerRadius = 6
        speedButton.layer.borderColor = UIColor.white.withAlphaComponent(0.21).cgColor
        speedButton.layer.borderWidth = CGFloat.app_lineHieght
        return speedButton
    }()
    private lazy var playListButton: CustomClickableView = {
        let playListButton = CustomClickableView()
        playListButton.setImage(UIImage(named: "story_play_list"))
        playListButton.setImageEdgeInsets(UIEdgeInsets(top: 22, left: 22, bottom: 22, right: 22))
        return playListButton
    }()
    private(set) lazy var speedListView = ScenicStorySpeedView()
    
}
